/**
 * Created by wxb on 2016/10/12.
 */
(function () {
  'use strict';

  angular.module('BlurAdmin.theme.components')
    .controller('ProductVideoUploadCtrl', ProductVideoUploadCtrl);

  /** @ngInject */
  function ProductVideoUploadCtrl($scope, $sce, $qupload, $log, qiniuToken, rfc4122, alertService) {
    var token;
    qiniuToken.productToken().then(function (data) {
      token = data.data.token;
    });
    // var baseUrl = qiniuToken.productBaseUrl();
    var baseUrl;
    qiniuToken.productBaseUrl().then(function (data) {
      baseUrl = data;
    });

    $scope.videoSelectFiles = [];
    $scope.videoUploading = false;

    var start = function (index) {
      $scope.videoSelectFiles[index].progress = {
        p: 0
      };
      $scope.videoSelectFiles[index].upload = $qupload.upload({
        key: $scope.key + rfc4122.v4() + '.' + $scope.videoSelectFiles[index].file.name.split(".").pop(),
        file: $scope.videoSelectFiles[index].file,
        token: token
      });
      $scope.videoSelectFiles[index].upload.then(function (response) {
        $log.info(response);
        $scope.videoUrl = baseUrl + response.key;
        $scope.formData.lessonVideo = response.key;
      }, function (response) {
        $log.info(response);
      }, function (evt) {
        $scope.videoSelectFiles[index].progress.p = Math.floor(100 * evt.loaded / evt.totalSize);
        $scope.videoProgressbarValue = $scope.videoSelectFiles[index].progress.p;
        if (evt) {
          $scope.videoUploading = true;
        }
        // if ($scope.videoSelectFiles[index].progress.p === 100) {
        //   $scope.uploading = false;
        // }

      });
    };

    $scope.abort = function (index) {
      $scope.videoSelectFiles[index].upload.abort();
      $scope.videoSelectFiles.splice(index, 1);
    };

    $scope.onFileSelect = function ($files) {
      var offsetx = $scope.videoSelectFiles.length;
      for (var i = 0; i < $files.length; i++) {
        $scope.videoSelectFiles[i + offsetx] = {
          file: $files[i]
        };
        start(i + offsetx);
      }
    };

    $scope.trustSrc = function(src) {
      return $sce.trustAsResourceUrl(src);
    };

    $scope.setInputAdress = function () {
      $scope.inputAdress = !$scope.inputAdress;
    };
    
    $scope.validate = function (url) {
      console.log(url, url.indexOf('http'))
      if (url.indexOf('http') > -1) {
        alertService.warning('只填七牛的资源key, 不是全路径!');
      }
      else {
        if (url.trim() !== '') {
          $scope.videoUrl = baseUrl + url;
        }
      }
    }

  }

})();










